<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ memberCount }}</div>
              <div class="stat-label">会员总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Goods /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ productCount }}</div>
              <div class="stat-label">商品总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ orderCount }}</div>
              <div class="stat-label">订单总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">¥{{ totalSales.toFixed(2) }}</div>
              <div class="stat-label">总销售额</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>最近订单</span>
          </template>
          <el-table :data="recentOrders" style="width: 100%">
            <el-table-column prop="orderNumber" label="订单号" width="120" />
            <el-table-column prop="finalAmount" label="金额" width="100">
              <template #default="scope">
                ¥{{ scope.row.finalAmount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>库存预警</span>
          </template>
          <el-table :data="lowStockProducts" style="width: 100%">
            <el-table-column prop="productCode" label="商品编码" width="120" />
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="stock" label="库存" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.stock === 0 ? 'danger' : 'warning'">
                  {{ scope.row.stock }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'Dashboard',
  setup() {
    const recentOrders = ref([])
    const lowStockProducts = ref([])
    const totalSales = ref(0)
    const memberCount = ref(0)
    const productCount = ref(0)
    const orderCount = ref(0)
    
    const fetchDashboardData = async () => {
      try {
        // 获取最近订单
        const ordersResponse = await fetch('/api/orders')
        const ordersData = await ordersResponse.json()
        recentOrders.value = ordersData.slice(0, 5)
        
        // 获取库存预警商品
        const lowStockResponse = await fetch('/api/products/low-stock?minStock=10')
        const lowStockData = await lowStockResponse.json()
        lowStockProducts.value = lowStockData
        
        // 计算总销售额
        totalSales.value = ordersData.reduce((sum, order) => sum + order.finalAmount, 0)
        
        // 获取统计数据
        const membersResponse = await fetch('/api/members')
        const membersData = await membersResponse.json()
        memberCount.value = membersData.length
        
        const productsResponse = await fetch('/api/products')
        const productsData = await productsResponse.json()
        productCount.value = productsData.length
        
        orderCount.value = ordersData.length
      } catch (error) {
        console.error('获取仪表盘数据失败:', error)
        ElMessage.error('加载数据失败，使用模拟数据')
        
        // 使用模拟数据
        recentOrders.value = [
          {
            orderNumber: 'ORD001',
            finalAmount: 25.50,
            status: 'COMPLETED',
            createTime: '2024-01-15 14:30:00'
          },
          {
            orderNumber: 'ORD002',
            finalAmount: 18.00,
            status: 'PENDING',
            createTime: '2024-01-15 16:20:00'
          }
        ]
        
        lowStockProducts.value = [
          {
            productCode: 'P001',
            name: '可口可乐',
            stock: 5
          },
          {
            productCode: 'P002',
            name: '康师傅方便面',
            stock: 0
          }
        ]
        
        totalSales.value = 12500.50
        memberCount.value = 150
        productCount.value = 200
        orderCount.value = 85
      }
    }
    
    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'COMPLETED': 'success',
        'CANCELLED': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待处理',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    onMounted(() => {
      fetchDashboardData()
    })
    
    onUnmounted(() => {
      // 清理组件状态
      recentOrders.value = []
      lowStockProducts.value = []
      totalSales.value = 0
      memberCount.value = 0
      productCount.value = 0
      orderCount.value = 0
    })
    
    return {
      memberCount,
      productCount,
      orderCount,
      totalSales,
      recentOrders,
      lowStockProducts,
      getStatusType,
      getStatusText
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  font-size: 48px;
  color: #409EFF;
  margin-right: 20px;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}
</style> 